﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;//输入输出
using Newtonsoft.Json;
using AiShow.Model;
using AiShow.BLL;
using AiShow.IBLL;

namespace AiShow.WebSite
{
    public partial class PersonalEdit : System.Web.UI.Page
    {
        private District District;
        public int userId;
        public IUserManager UserManager = new UserManager();
        private void BinProvince(string ProvinceName) 
        {
            ddlProvince.DataSource = District.Provinces;
            ddlProvince.DataTextField = "ProvinceName";
            ddlProvince.DataValueField = "ProvinceName";
            ddlProvince.DataBind();
            //默认选项
            ddlProvince.Items.Insert(0,"-请选择-");

            if (string.IsNullOrEmpty(ProvinceName))
            {
                ddlProvince.SelectedIndex = 0;
            }
            else {
                ddlProvince.SelectedValue = ProvinceName;
            }
            
        }
        private void BindCity(string ProvinceName,string CityName)
        {
            var Province = District.Provinces.SingleOrDefault(p=>p.ProvinceName==ProvinceName);
            if (Province!=null) {
                ddlCity.DataSource = Province.Citys;
                ddlCity.DataValueField = "CityName";
                ddlCity.DataTextField = "CityName";
                ddlCity.DataBind();
            }
            ddlCity.Items .Insert(0, "-请选择-");
            if (string.IsNullOrWhiteSpace(CityName))
            {
                ddlCity.SelectedIndex = 0;
            }
            else {
                ddlCity.SelectedValue = CityName;
            }
        }
        /// <summary>
        /// 获取全部信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //MapPath 读取全部内容/App_Data/district.json
            var file = Server.MapPath("~/App_Data/district.json");
           var text= File.ReadAllText(file,System .Text .Encoding.Default);
            //反序列化
           District=  JsonConvert.DeserializeObject<District>(text);
            if (!IsPostBack)
            {
                var ProvinceName = "ProvinceName";
                var CityName = "ProvinceName, CityName";
                
                var user = IdentityManager.ReadUser();
                if (user == null)
                {
                    //自动跳转
                    Response.Redirect("login.aspx?ReturnUrl=Personal.aspx");
                }
                else
                {
                    //userId = user.Id;
                    //处理省市
                    if (!string .IsNullOrWhiteSpace(user.Address)) {
                        //数据分割判断（用空格进行分割）
                        string[] addressArray = user.Address.Split(' ');
                        if (addressArray.Length == 2) {
                            ProvinceName = addressArray[0];
                            CityName = addressArray[1];
                        }
                    }
                    //兴趣爱好
                    if (!string .IsNullOrWhiteSpace(user .Hobby))
                    {
                        //数据分割判断（用,进行分割）
                        string[] hobbys = user.Hobby.Split(',');
                        foreach (ListItem item in cblHobby.Items )
                        {
                            var hobby = item.Text;
                            //Any确认序列中的元素是否都满足条件
                            item.Selected=  hobbys.Any(p=>p==hobby);
                        }
                    }
                    //编辑
                    txtNickName.Text = user.NickName;
                    //生日
                    txtBirthday.Text = user.Birthday?.ToString("yyyy-MM-dd");
                    //性别
                    ddlSex.SelectedValue = user.Sex.ToString();
                }
                BinProvince(ProvinceName);
                BindCity(ProvinceName, CityName);
            }
        }
        protected void btnProfile_Click(object sender, EventArgs e)
        {
            // var user = new TBUsers
            
                var user = IdentityManager.ReadUser();
                user.NickName = txtNickName.Text;
                user.Address = ddlProvince.SelectedValue + "" + ddlCity.SelectedValue;
                user.Birthday = Convert.ToDateTime(txtBirthday.Text);
                user.Sex = Convert.ToInt32(ddlSex.SelectedValue);
                // Id = userId

                string hobby = "";
                foreach (ListItem item in cblHobby.Items)
                {
                    if (item.Selected)
                    {
                        hobby += item.Text + ",";
                    }
                }

                user.Hobby = hobby.Substring(0, hobby.Length - 1);
                var result = UserManager.EditWithoutAvatar(user);
                if (result.StatusCode == Common.StatusCode.Succeed)
                {
                    Response.Redirect("Personal.aspx");
                }
                else
                {
                    ClientScript.RegisterStartupScript(GetType(), "editerror", $"alert('{result.Message}')", true);

                }
            
        }
        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            var p = ddlProvince.SelectedValue;
            BindCity(p,"");
        }
    }
}